﻿using Microsoft.AspNetCore.Http;

namespace ProgrammingEducationSystem.Tools
{
    public static class FileTools
    {
        public static async Task<string?>? UpFile(IFormFile file,string filepatch) {
            try
            {
                if (file == null || file.Length <= 0)return null;
                if (!Directory.Exists(filepatch)) {
                    Directory.CreateDirectory(Path.GetDirectoryName(filepatch));
                }
                var fs = new FileStream(filepatch, FileMode.Create);
                await file.CopyToAsync(fs);
                fs.Close();
                return filepatch.Replace("wwwroot/", "");
            }
            catch (Exception err)
            {
                Console.WriteLine(err);
                return null;
            }
        }

        public static string GenerYMD() 
        {
            DateTime dt = DateTime.UtcNow;
            var year = dt.Year;
            var month = dt.Month;
            var day = dt.Day;
            return "Y"+ year+"/M" + month+"/D" + day;
        }

        /// <summary>
        /// 生成头像路径
        /// </summary>
        /// <returns></returns>
        public static string GenerAvatarPath(string ext) 
        {
            
            var fileName = "A"+Guid.NewGuid() + "." + ext;
            var path = Path.Combine("wwwroot/avatar",GenerYMD(),fileName);
            return path;
        }

        /// <summary>
        /// 生成学习资源路径
        /// </summary>
        /// <param name="ext"></param>
        /// <returns></returns>
        public static string GenerLearnSourcePath(string ext) 
        {
            var fileName = "L"+Guid.NewGuid() + "." + ext;
            var path = Path.Combine("wwwroot/learnsource", GenerYMD(), fileName);
            return path;
        }


    }
}
